//
//  UITextView+RACAttribute.m
//  OSChina
//
//  Created by 8b410-2 on 17/1/9.
//  Copyright © 2017年 abb. All rights reserved.
//

#import "UITextView+RACAttribute.h"
#import "RACEXTScope.h"
#import "NSObject+RACDeallocating.h"
#import "NSObject+RACDescription.h"
#import "RACDelegateProxy.h"
#import "RACSignal+Operations.h"
#import "RACTuple.h"
#import <objc/runtime.h>

@implementation UITextView (RACAttribute)

static void RACUseDelegateProxy(UITextView *self) {
    if (self.delegate == self.rac_delegateProxy) return;
    
    self.rac_delegateProxy.rac_proxiedDelegate = self.delegate;
    self.delegate = (id)self.rac_delegateProxy;
}

- (RACSignal *)rac_attributeTextSignal {
    @weakify(self);
    RACSignal *signal = [[[[[RACSignal
                             defer:^{
                                 @strongify(self);
                                 return [RACSignal return:RACTuplePack(self)];
                             }]
                            concat:[self.rac_delegateProxy signalForSelector:@selector(textViewDidChange:)]]
                           reduceEach:^(UITextView *x) {
                               return x.attributedText;
                           }]
                          takeUntil:self.rac_willDeallocSignal]
                         setNameWithFormat:@"%@ -rac_attributeTextSignal", self.rac_description];
    
    RACUseDelegateProxy(self);
    
    return signal;
}
@end
